package com.atsmart.app.activity;

import java.io.IOException;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.adapter.LoadingAdapter;
import com.atsmart.app.adapter.ReportListAdapter;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.model.ClientPageInfo;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.TemplateInfo;
import com.atsmart.app.model.TemplateListInfo;
import com.atsmart.app.utils.IntentUtil;
import com.atsmart.app.utils.PersistentKeyUtil;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;
import com.google.json.JsonParseException;

public class ClientReportListActivity extends BaseActivity implements
		LoadingAdapter.Delegate, LoadingAdapter.OnLoadingRowShowingHandler {
	private static final String TAG = ClientReportListActivity.class.getName();

	private ListView listView;
	private TemplateListInfo datasource;
	private ReportListAdapter adapter;
	private static final int pageSize = 20;
	private boolean isNeedLoading = false;
	private int totalRow;
	private int pageIndex = 0;
	private int clientId;
	private boolean asyntaskIsFinished = false;
	private Button btnRefresh;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.client_report_list_layout);
		clientId = getIntent().getIntExtra(PersistentKeyUtil.CLIENT_ID_STRING, 0);
		if (clientId == 0) {
			this.finish();
			return;
		}
		btnRefresh = (Button) findViewById(R.id.btn_refresh);
		btnRefresh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (asyntaskIsFinished) {
					showLoading();
					pageIndex = 0;
					getData();
					asyntaskIsFinished = false;
				}
			}
		});
		listView = (ListView) findViewById(R.id.listview);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> partent, View view,
					int position, long id) {
				if (adapter == null) {
					return;
				}
				TemplateInfo templateInfo = (TemplateInfo) adapter
						.getItem(position);
				if (templateInfo == null) {
					return;
				}
				Bundle bundle = new Bundle();
				bundle.putInt(PersistentKeyUtil.REPORT_TYPE, PersistentKeyUtil.REPORT_TYPE_CLIENT);
				bundle.putInt(PersistentKeyUtil.TEMPLATE_ID_STRING, templateInfo.getId());
				bundle.putString(PersistentKeyUtil.TEMPLATE_NAME, templateInfo.getName());
				bundle.putInt(PersistentKeyUtil.CLIENT_ID_STRING, clientId);
				IntentUtil.redirectToNext(ClientReportListActivity.this, ReportActivity.class, bundle);
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (pageIndex == 0 && totalRow == 0) {
			showLoading();
			getData();
		}
	}

	private int isPage =  0;
	private void getData() {
		registerLoadStatus(TAG);
		new ServiceAsynTask<TemplateListInfo>() {

			@Override
			protected TemplateListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException ,Exception{
				if(pageIndex == 0){
					isPage = 0;
				}else{
					isPage ++;
				}
				CommonBody body = new CommonBody();
		    	body.setCommand(2);
		    	body.setImsi(BizApp.getInstance().getIMSI());
		    	body.setVersion("1.0");
				ClientPageInfo pageInfo = new ClientPageInfo();
				pageInfo.begin = pageIndex * pageSize + isPage;
//				pageInfo.end = (pageIndex + 1) * pageSize - 1;
				pageInfo.end = (pageIndex + 1) * pageSize + isPage;
				pageInfo.clientId = clientId;
				Gson gson = new Gson();
				return ServiceHelper.getInstance().postData(
						ServiceHost.getTemplateURL(),
						gson.toJson(body), gson.toJson(pageInfo), TemplateListInfo.class);
			}

			@Override
			protected void runWithResult(TemplateListInfo result)
					throws Exception {
				if (result != null) {
					datasource = result;
					bindData();
				}
				ReportForAllActivity.hideLoading();
				finishedLoad(TAG);
				asyntaskIsFinished = true;
			}

			@Override
			protected void runWithError(TemplateListInfo result, int iErrorCode)
					throws Exception {
				loadingFailed(TAG, iErrorCode);
				asyntaskIsFinished = true;
				//hideLoading();
			}
		}.execute();
	}

	private void bindData() {
		if (adapter == null || pageIndex == 0) {
			adapter = new ReportListAdapter(datasource);
			adapter.setDelegate(this);
			adapter.setHandler(this);
			listView.setAdapter(adapter);
		} else {
			if (pageIndex >= 1) {
				adapter.appendDataSource(datasource);
				adapter.notifyDataSetChanged();
			}
		}
		totalRow = datasource.getRows();
		if (totalRow > (pageIndex + 1) * pageSize) {
			isNeedLoading = true;
		} else {
			isNeedLoading = false;
		}
	}

	@Override
	public void onLoadingRowShowing(LoadingAdapter adapter) {
		if (pageIndex * pageSize < totalRow) {
			if (asyntaskIsFinished) {
				pageIndex++;
				getData();
				asyntaskIsFinished = false;
			}
		}
	}

	@Override
	public boolean needLoading() {
		return isNeedLoading;
	}
}
